package com.tgjs.sphoto.request;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.tgjs.sphoto.constant.ConstantValues;
import com.tgjs.sphoto.utils.JsonUtil;


import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/4.
 */

public class HttpRequest {

    private Handler handler;
    private ProgressDialog progressDialog;
    private Context context;
    private static final String TAG = "HttpRequest";


    public HttpRequest(Handler handler, Context context) {
        this.handler = handler;
        progressDialog = new ProgressDialog(context);
        this.context = context;
    }

    public void postDataString(final String url, final int what, final String tag, final Map<String, String> paramsMap, boolean isShowProgress, @Nullable String progressMsg) {
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
      /*  if (paramsMap != null){
            paramsMap.put("Authorization", SPUtils.getInstance().getString(ConstantValues.TOKEN));
        }*/
        OkGo.<String>post(url)
                .headers("Authorization", SPUtils.getInstance().getString(ConstantValues.TOKEN))
                .params(paramsMap, true)
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OkGo.cancelTag(OkGo.getInstance().getOkHttpClient(),tag);
                        progressDialog.dismiss();
                             Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())) {
                            msg.obj = response.body().toString().trim();
                        } else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }

    public void postDataStringWithoutToken(final String url, final int what,final String tag, final Map<String, String> paramsMap, boolean isShowProgress, @Nullable String progressMsg) {
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
        OkGo.<String>post(url)
                .params(paramsMap, true)
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OkGo.cancelTag(OkGo.getInstance().getOkHttpClient(),tag);
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())) {
                            msg.obj = response.body().toString().trim();
                        } else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }

    public void getDataString(final String url, final int what, boolean isShowProgress, @Nullable String progressMsg){
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
        OkGo.<String>get(url)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())) {
                            msg.obj = response.body().toString().trim();
                        } else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }

    public void getDataStringWithCustomHead(final String url, final int what, boolean isShowProgress, @Nullable String progressMsg,HttpHeaders headers){
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
        OkGo.<String>get(url)
                .headers(headers)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())) {
                            msg.obj = response.body().toString().trim();
                        } else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }

    public void postDataStringWithFile(final String url, final int what,final String tag, final Map<String,String> paramsMap, boolean isShowProgress, @Nullable String progressMsg,List<File> fileList){
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
        if (paramsMap != null){
            paramsMap.put("token", SPUtils.getInstance().getString(ConstantValues.TOKEN));
        }
        OkGo.<String>post(url)
                .params(paramsMap,true)
                .addFileParams("files",fileList)
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OkGo.cancelTag(OkGo.getInstance().getOkHttpClient(),tag);
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())){
                            msg.obj = response.body().toString().trim();
                        }else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }

    public void downLoadFile(String url,final int what,String dir,String fileName,boolean isShowProgress){
        if (isShowProgress){
            progressDialog = ProgressDialog.show(context,"","加载中！");
        }
        dir = Environment.getExternalStorageDirectory().getPath()+dir;
        File file = new File(dir);
        if (!file.exists()){
            file.mkdirs();
        }
        OkGo.<File>get(url).execute(new FileCallback(dir, fileName) {
            @Override
            public void onSuccess(Response<File> response) {
                progressDialog.dismiss();
                Message msg = handler.obtainMessage();
                msg.what = what;
                msg.obj = response.body();
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Response<File> response) {
                progressDialog.dismiss();
                Message msg = handler.obtainMessage();
                msg.what = what;
                msg.arg1 = -1;
                handler.sendMessage(msg);
                super.onError(response);
            }
        });
    }

    private void writeErrorLog(String filePath, String url, Map<String,String> paramsMap, String token, String content){
        if (FileUtils.createOrExistsFile(filePath)){
            File file = new File(filePath);
            FileIOUtils.writeFileFromString(file,"\r\n",true);
            FileIOUtils.writeFileFromString(file,url,true);
            FileIOUtils.writeFileFromString(file,"\r\n",true);
            if (paramsMap!=null && paramsMap.size()>0){

                StringBuffer sb = new StringBuffer();
                for (Map.Entry<String,String> entry : paramsMap.entrySet()){
                    sb.append(entry.getKey()+"="+entry.getValue()+";");
                }
                FileIOUtils.writeFileFromString(file,sb.toString(),true);
            }
            FileIOUtils.writeFileFromString(file,"\r\n"+token+"\r\n",true);
            FileIOUtils.writeFileFromString(file,content,true);
            FileIOUtils.writeFileFromString(file,".............................................................................................."
                    ,true);
        }
    }
    public void postDataJson(final String url, final int what, final String tag, final Map<String, String> paramsMap, boolean isShowProgress, @Nullable String progressMsg) {
        if (isShowProgress) {
            progressDialog = ProgressDialog.show(context, "", TextUtils.isEmpty(progressMsg)?"加载中":progressMsg);
        }
        if (paramsMap != null){
            paramsMap.put("token", SPUtils.getInstance().getString(ConstantValues.TOKEN));
        }
        JSONObject jsonObject = new JSONObject(paramsMap);
        OkGo.<String>post(url)
                .upJson(jsonObject.toString())
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OkGo.cancelTag(OkGo.getInstance().getOkHttpClient(),tag);
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        //判断返回数据是否为json，如果不是先把url和传参和token写入本地文件，方便调试
                        if (JsonUtil.isJsonValid(response.body().toString().trim())) {
                            msg.obj = response.body().toString().trim();
                        } else {
                            msg.arg1 = -1;
                        }
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        progressDialog.dismiss();
                        Message msg = handler.obtainMessage();
                        msg.what = what;
                        msg.arg1 = -1;
                        handler.sendMessage(msg);
                        super.onError(response);
                    }
                });
    }
}
